<template>
    <view class="chatInfo-main">
        <view class="header-cont">
            <uni-icons type="left" size="30" @click="back()"></uni-icons>
            <view class="accountName">{{ friend?.name }}</view>
        </view>

        <view class="chat-container">
            <view class="chat" ref="chat">
                <list v-for="i in chatInfoList" :key="i.id">
                    <view v-if="i.accountId !== account?.id" class="chatInfo">
                        <image :src="i.avatar" class="image" mode="aspectFill"></image>
                        <view class="textViewContainer">
                            <view class="textView">
                                <text class="t">{{ i.content }}</text>
                            </view>
                        </view>
                    </view>
                    <view v-else class="chatInfo reverse">
                        <image :src="i.avatar" class="image" mode="aspectFill"></image>
                        <view class="textViewContainer">
                            <view class="textView">
                                <text class="t">{{ i.content }}</text>
                            </view>
                        </view>
                    </view>
                </list>
            </view>
        </view>

        <view class="chatBox">
            <textarea class="content" v-model="content" maxlength="-1" auto-height @input="adjustHeight"
                @keypress.enter="sendMsg(1, 1)" :style="{ height: textareaHeight + 'px' }"></textarea>
            <button class="mini-btn sendButton" type="primary" size="mini" @click="sendMsg(1, 1)" :disabled="sending">发送
            </button>
        </view>
    </view>
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { getCurrentInstance, ref, type Ref, nextTick } from 'vue';
import { request } from '@/api/request';
import type { chatInfoDto } from "@/api/model/chat/chatInfoDto";
import type { AccountDto } from "@/api/model/account/AccountDto";
import { WEB_SOCKET } from '@/api/request';

const currentInstance = getCurrentInstance();
const value = ref('');
const roomId = ref('');
let content = ref('');
const textareaHeight = ref(20);
const userId = ref('');
const sending = ref(false);
const chatInfoList: Ref<chatInfoDto[]> = ref([]);
const account: Ref<AccountDto | undefined> = ref();
const friend: Ref<AccountDto | undefined> = ref();


onLoad(async (option) => {
    account.value = uni.getStorageSync('account');
    roomId.value = option?.roomId;

    const operation = {
        method: 'get',
        url: `/main/account/get/${option?.friendId}`,
        data: '',
        tokenRequired: true // 新增，表示是否需要token
    };
    const res = await request(operation);
    friend.value = res.data.account


    uni.connectSocket({
        url: `{WEB_SOCKET}/${roomId.value}-${friend.value?.id}`,
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        success() {
            console.log('WebSocket连接成功');
        },
        fail(err) {
            console.error('WebSocket连接失败', err);
        }
    });
    //刚进入时先判断是否有新的对话，没有就拿store的数据，有就获取新的聊天记录，存入store
    // 先从store拿数据，没有就从数据库拿
    chatInfoList.value = uni.getStorageSync(`chat-${option?.roomId}-${friend.value?.id}`);
    const lastElement = chatInfoList.value[chatInfoList.value.length - 1];
    if (chatInfoList.value.length === 0) {
        findChatInfo(option?.roomId);
    } else {
        findNewChat(option?.roomId, lastElement.id)
    }
    nextTick(() => scrollToBottom());
});


uni.onSocketOpen(function () {
    console.log('WebSocket连接已打开');
});

uni.onSocketMessage(function (res) {
    console.log(JSON.stringify(res))
    const chatDto: chatInfoDto = JSON.parse(res.data);
    chatInfoList.value.push(chatDto);
    nextTick(() => scrollToBottom());
});

uni.onSocketError(function (err) {
    console.error('WebSocket错误：', err);
});

uni.onSocketClose(function () {
    console.log('WebSocket连接已关闭');
});

const sendMsg = async (msgType: number, type: number) => {
    if (!content.value.trim() || sending.value) return;
    sending.value = true;
    const data = {
        roomId: roomId.value,
        content: content.value,
        msgType: msgType,
        type: type
    };

    const operation = {
        method: 'POST',
        url: `/main/chat/create`,
        data: data,
        tokenRequired: true // 新增，表示是否需要token
    };

    try {
        const res = await request(operation);
        content.value = '';
        //chatInfoList.value.push(res.data.chat);
        textareaHeight.value = 20;
        nextTick(() => scrollToBottom());
    } catch (error) {
        console.error('发送消息失败', error);
    } finally {
        sending.value = false;
    }
};

const findChatInfo = async (roomId: string) => {
    const data = { roomId: roomId };
    const operation = {
        method: 'GET',
        url: `/main/chat/find`,
        data: data,
        tokenRequired: true // 新增，表示是否需要token
    };
    const res = await request(operation);
    chatInfoList.value = res.data.chatDto;
    uni.setStorage({
        key: `chat-${roomId}-${friend.value?.id}`,
        data: chatInfoList.value
    })
    nextTick(() => scrollToBottom());
};

const findNewChat = async (roomId: string, chatId: string) => {
    const data = { roomId: roomId, chatId: chatId };
    const operation = {
        method: 'GET',
        url: `/main/chat/haveNewChatList`,
        data: data,
        tokenRequired: true // 新增，表示是否需要token
    };
    const res = await request(operation);
    chatInfoList.value = chatInfoList.value.concat(res.data.chatDto)
    //chatInfoList.value=[...chatInfoList.value,...res.data.chatDto]
    uni.setStorage({
        key: `chat-${roomId}-${friend.value?.id}`,
        data: chatInfoList.value
    })
    nextTick(() => scrollToBottom());
};



const back = () => {
    
    uni.closeSocket({
            success() {
                console.log('WebSocket连接已关闭');

            },
            fail(err) {
                console.error('关闭WebSocket连接失败', err);
            }
        });
    uni.navigateBack({
        delta: 1
    });
};

const adjustHeight = (event: { target: any; }) => {
    const textarea = event.target;
    textareaHeight.value = Math.min(textarea.scrollHeight, 200); // 限制最大高度为200px
};

const scrollToBottom = () => {
    const chatElement = document.querySelector('.chat');
    if (chatElement) {
        chatElement.scrollTop = chatElement.scrollHeight;
    }
};
</script>

<style lang="scss">
.chatInfo-main {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.header-cont {
    display: flex;
    text-align: center;
    align-items: center;
    width: 100%;
    height: 8%;
    background: #F1F5FF;
    justify-content: left;

    .accountName {
        font-size: 20px;
        font-family: "宋体", serif;
        bottom: 100px;
    }
}

.chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.chat {
    flex: 1;
    overflow-y: auto;
    background-color: #eeedf2;
    padding-bottom: 1rem;
}

.chatBox {
    display: flex;
    align-items: end;
    background: #F1F5FF;
    padding: 10px;
}

.content {
    flex: 1;
    margin: 14px;
    background-color: white;
    border-radius: 5%;
    caret-color: #01B4FE;
    min-height: 30px;
    overflow: hidden;
    font-size: 20px;
    align-items: center;
}

.sendButton {
    margin-bottom: 15px;
}

.image {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin: 5px 10px 0 5px;
}

.chatInfo {
    display: flex;
    flex-direction: row;
    width: auto;
    height: auto;
    margin-bottom: 10px;
    min-height: 20px;
    word-wrap: break-word; // 自动换行
    word-break: break-all;
    white-space: normal;

    .textViewContainer {
        padding-top: 10px;

        .textView {
            border-radius: 5%;
            padding: 10px;
            margin-top: 10px;
            margin-bottom: 10px;
            background-color: white;
            width: auto;
            max-width: 280px;
        }
    }
}

.reverse {
    flex-direction: row-reverse;
}
</style>
